<?php

namespace app\system\controller;

use app\common\model\DictClassModel;

class DictClassController extends BaseController
{

  /**
   * 无需登录的方法
   * @var array
   */
  protected $noLogin = [];

  /**
   * 不需要检测权限的方法
   * @var array
   */
  protected $noCheck = [];

  /**
   * 权限映射
   * @var array
   */
  protected $mapCheck = [
    '*' => 'dict/index'
  ];

  /**
   * 当前模型
   * @var null
   */
  protected $model = null;

  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->model = new DictClassModel();
  }

  /**
   * 获取分组数据
   * @return mixed
   * @throws \Exception
   */
  public function index()
  {
    $list = $this->model->getList();
    foreach ($list as $k => $v) {
      $list[$k]['name'] = "{$v['name']}({$v['code']})";
    }
    return json($list);
  }

  /**
   * 添加
   * @return string
   * @throws \Exception
   */
  public function add()
  {
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data, [
        'code|分类编码' => 'require',
        'name|分类名称' => 'require',
      ]);
      $this->model->add($data);
      $this->success('操作成功');
    }
    $class = $this->model->where('pid', 0)->order('show_order asc')->select();
    $this->assign('class', $class);
    return $this->fetch();
  }

  /**
   * 编辑
   * @return string
   * @throws \Exception
   */
  public function edit()
  {
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data, [
        'code|分类编码' => 'require',
        'name|分类名称' => 'require',
      ]);
      $this->model->edit($data);
      $this->success('操作成功');
    }
    $id = $this->request->param('id/d');
    $info = $this->model->where('id', $id)->find();
    $class = $this->model->where('pid', 0)->order('show_order asc')->select();
    $this->assign('info', $info);
    $this->assign('class', $class);
    return $this->fetch();
  }

  /**
   * 删除
   * @return string
   * @throws \Exception
   */
  public function del()
  {
    $id = $this->request->param('id/d');
    $this->model->del($id);
    $this->success('操作成功');
  }
}
